package mdoc.tp1;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import domain.Contact;
import domain.Entreprise;
import domain.DAO.DAOContact;
import domain.DAO.DAOFactory;
import domain.interfaces.IDAOContact;
import domain.interfaces.IDAOEntreprise;

/**
 * Servlet implementation class LoadContacts
 */
public class LoadAllContacts extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoadAllContacts() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		ServletContext ctx = getServletContext();
		IDAOContact DAOC = DAOFactory.getDAOContact(ctx);
		IDAOEntreprise DAOE = DAOFactory.getDAOEntreprise(ctx);
		Set<Entreprise> se = DAOE.findAll();
		
		request.setAttribute("Contacts", retrieveContacts(DAOC.findAll(), se));
		request.setAttribute("Entreprises", se);
		request.getRequestDispatcher("main.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	public Set<Contact> retrieveContacts(Set<Contact> sc, Set<Entreprise> se)
	{
		Set<Contact> sres = new HashSet<Contact>();
		for (Contact c : sc) {
			for (Entreprise e : se) {
				if (c.getId() == e.getId()){
					sres.add(c);	
				}
			}
		}
		sc.removeAll(sres);
		return sc;
	}
}
